from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings


def generate_openid_signature(openid):
    """
    对openid进行加密
    :param openid:
    :return:  加密后的openid
    """

    # serializer = Serializer(秘钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, 360)
    # serializer.dumps(数据), 返回bytes类型,传字典类型数据
    openid_sign = serializer.dumps({'openid': openid})

    return openid_sign.decode()

def check_openid_sign(openid_sign):
    """解密,回到将加密前数据的样子"""
    serializer = Serializer(settings.SECRET_KEY, 360)
    try:
        data = serializer.dumps(openid_sign)

    # 验证失败，会抛出itsdangerous.BadData异常
    except BadData:
        return None

    return data.get('openid')